<template>
    <van-empty v-if="!usercarts.length" image="https://fastly.jsdelivr.net/npm/@vant/assets/custom-empty-image.png"
        image-size="80" description="描述文字" />
    <div v-else>
        <van-swipe-cell v-for="item in usercarts">
            <van-card :price="item.goods.goods_price" :title="item.goods.goods_name" class="goods-card">
                <template #thumb>
                    <van-checkbox v-model="item.checked"></van-checkbox>
                    <van-image width="100" height="100" :src="item.goods.goods_small_logo" />
                </template>
                <template #num>
                    <van-stepper v-model="item.number" theme="round" button-size="22" disable-input />
                </template>
            </van-card>
            <template #right>
                <van-button @click="detail(item.id)" square text="删除" type="danger" class="delete-button" />
            </template>
        </van-swipe-cell>
    </div>
    <van-submit-bar :price="allprice" button-text="提交订单" @submit="onSubmit">
        <van-checkbox v-model="AllCart">全选</van-checkbox>
    </van-submit-bar>


</template>
<script setup>
import { computed, ref } from 'vue';
import { useCounterStore } from '@/stores/cart'
// 可以在组件中的任意位置访问 `store` 变量 ✨
const store = useCounterStore()
console.log(store.carts);

let usercarts = ref([])
const data = () => {
    let username = localStorage.getItem('username')
    usercarts.value = store.carts.filter((item) => item.username == username)
}
data()

const detail = (id) => {
    store.detail(id)
    data()
}
const AllCart = computed({
    get() {
        if (usercarts.value.length === 0) {
            return false
        }
        else {
            return usercarts.value.every(item => item.checked)
        }
    },
    set(val) {
        return usercarts.value.forEach((item) => item.checked = val)
    }
})
const allprice = computed(() => {
    let allprice = 0
    let cartok = usercarts.value.filter((item) => item.checked)
    cartok.forEach((item) => {
        allprice += item.number * item.goods.goods_price
    })
    return allprice * 100
})

import { CreateOrderApi } from '@/api/api'
import { useRouter } from 'vue-router';
let router = new useRouter()

const onSubmit = () => {
    let orderok = usercarts.value.filter((item) => item.checked)
    CreateOrderApi({
        goodsIds: orderok.map(item => item.goods.goods_id).join(','),
        username: localStorage.getItem('username'),
        product_code: orderok[0].goods.goods_name,
        totalPrice: allprice.value,
        nums: orderok.map(item => item.number).join(',')
    }).then(res => {
    console.log(res);
    router.push('/order/' + res.data.data.orderId)
  })
}
</script>

<style lang="scss" scoped></style>